package com.ktjiaoyu.ktmall.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

/**
 * @author xm
 * @date 2025/9/17
 * @Dome
 */
public class OSSUtil {
    private static final String ENDPOINT = "oss-cn-guangzhou.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tBjanHTeEkYVPGgpGpk";
    private static final String ACCESS_KEY_SECRET = "B07G6cZrDYafy1aV0m9d4IJOAsOVgv";
    private static final String BUCKET = "ktmall2025913";

    private static final String HOST = "https://" + BUCKET + "." + ENDPOINT;

    public static JSONObject getPolicy() {
        try {
            // 延长有效期到10分钟（600秒）
            long expireTime = 600;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            JSONObject policy = new JSONObject();
            policy.put("expiration", toGMTString(expiration));

            JSONArray conditions = new JSONArray();

            // 添加大小限制条件
            JSONArray sizeCondition = new JSONArray();
            sizeCondition.add("content-length-range");
            sizeCondition.add(0);
            sizeCondition.add(10485760); // 10MB
            conditions.add(sizeCondition);

            // 添加路径前缀条件
            JSONArray startsWithCondition = new JSONArray();
            startsWithCondition.add("starts-with");
            startsWithCondition.add("$key");
            startsWithCondition.add("images/");
            conditions.add(startsWithCondition);

            policy.put("conditions", conditions);

            JSONObject result = new JSONObject();
            String policyString = policy.toString();

            // 使用UTF-8编码
            String encodePolicy = Base64.getEncoder().encodeToString(
                    policyString.getBytes(StandardCharsets.UTF_8));

            String signature = hmacSHA1Signature(ACCESS_KEY_SECRET, encodePolicy);

            result.put("accessid", ACCESS_KEY_ID);
            result.put("policy", encodePolicy);
            result.put("signature", signature);
            result.put("dir", "images/");
            result.put("host", HOST);
            result.put("expire", String.valueOf(expireEndTime / 1000));

            // 添加调试信息
            System.out.println("生成的OSS策略: " + policyString);
            System.out.println("策略过期时间: " + toGMTString(expiration));

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String hmacSHA1Signature(String secret, String baseString) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
        mac.init(keySpec);
        byte[] rawHmac = mac.doFinal(baseString.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(rawHmac);
    }

    private static String toGMTString(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        return df.format(date);
    }
}